//
//  HMHomePictureView.swift
//  Weibo
//
//  Created by teacher on 2017/6/10.
//  Copyright © 2017年 teacher. All rights reserved.
//

import UIKit
import SDWebImage

//  设置每项间距
private let ItemMargin: CGFloat = 5
//  计算每项的宽度
private let ItemWidth: CGFloat = (ScreenWidth - 2 * HomeCellMargin - 2 * ItemMargin) / 3

//  自定义首页配图
class HMHomePictureView: UICollectionView {

    //  图片数据源
    var picUrls: [HMHomePicInfo]? {
        didSet {
            messageLabel.text = "\(picUrls?.count ?? 0)"
            
            guard let currentPicurls = picUrls else {
                return
            }
            
            //  根据图片的张数计算配图的大小
            calcPictureViewSize(count: currentPicurls.count)
            
            //  数据源变化，需要重新加载数据
            reloadData()
        }
    }
    
    //  MARK: --懒加载控件
    private lazy var messageLabel: UILabel = {
        let label = UILabel(fontSize: 20, textColor: UIColor.red)
        return label
    }()
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        
        let flowLayout = UICollectionViewFlowLayout()
        //  设置cell的大小
        flowLayout.itemSize = CGSize(width: ItemWidth, height: ItemWidth)
        //  设置垂直方向的最小行间距
        flowLayout.minimumLineSpacing = ItemMargin
        //  设置水平方向的最小行间距
        flowLayout.minimumInteritemSpacing = ItemMargin
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
        
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUpUI() {
        //  注册cell
        register(HMHomePictureViewCell.self, forCellWithReuseIdentifier: HomePictureViewCellIdentifer)
        //  设置数据源代理
        dataSource = self
        //  设置代理
        delegate = self
        addSubview(messageLabel)
        messageLabel.snp.makeConstraints { (make) in
            make.center.equalTo(self)
        }
    }
    
    //  根据图片的张数计算配图的大小
    private func calcPictureViewSize(count: Int) {
        
        //  判断是否是单张图片
        if count == 1 {
            //  单张图片的地址
            let imageUrl = picUrls!.first!.thumbnail_pic!
            //  单张图片
            if let localImage = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: imageUrl) {
                //  我们只是默认处理单张图片，正常来说这个大小应该由服务端给我们提供
                //  获取大小
                var imageSize = localImage.size
                //  图片过窄
                if imageSize.width < 80 {
                    let currentWidth: CGFloat = 80
                    //  计算高度
                    var currentheight = currentWidth / imageSize.width * imageSize.height
                    //  过高
                    if currentheight > 150 {
                        currentheight = 150
                    }
                    //  计算好的大小
                    imageSize = CGSize(width: currentWidth, height: currentheight)
                }
                
                //  找到单张图片
                self.snp.updateConstraints({ (make) in
                    //  把单张图片的大小作为配图的大小
                    make.size.equalTo(imageSize).priority(.high)
                })
                
                // 修改配图item的大小
                let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
                flowLayout.itemSize = imageSize
                
                return
            }
            
        }
        
        //  代码执行到此表示不是单张图片
        
        //  列数计算
        let cols = count > 3 ? 3 : count
        
        //  行数计算
        let rows = (count - 1) / 3 + 1
        
        //  计算配图宽度
        let pictureViewWidth = CGFloat(cols) * ItemWidth + CGFloat(cols - 1) * ItemMargin
        
        //  计算配图高度
        let pictureViewHeight =  CGFloat(rows) * ItemWidth + CGFloat(rows - 1) * ItemMargin
        
        //  当前配图大小
        let pictureViewSize = CGSize(width: pictureViewWidth, height: pictureViewHeight)
        
        //  更新配图大小
        self.snp.updateConstraints { (make) in
            make.size.equalTo(pictureViewSize).priority(.high)
        }
        
        //  不是单张图片，需要设置成为计算好的配图item的大小
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = CGSize(width: ItemWidth, height: ItemWidth)
    }
}

//  MARK:   --UICollectionViewDataSource 
extension HMHomePictureView: UICollectionViewDataSource, UICollectionViewDelegate, SDPhotoBrowserDelegate {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: HomePictureViewCellIdentifer, for: indexPath) as! HMHomePictureViewCell
        //  赋值模型显示图片数据
        cell.picInfo = picUrls![indexPath.item]
        
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        
        let photoBrowser = SDPhotoBrowser()
        photoBrowser.delegate = self
        photoBrowser.currentImageIndex = indexPath.item
        photoBrowser.imageCount = picUrls!.count
        photoBrowser.sourceImagesContainerView = self
        photoBrowser.show()
        
    }
    //  返回高清的url
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        let urlStr = picUrls![index].thumbnail_pic!.replacingOccurrences(of: "thumbnail", with: "bmiddle")
        
        return URL(string: urlStr)
    }
    //  返回占位图片
    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
      
        let cell = self.cellForItem(at: IndexPath(item: index, section: 0)) as! HMHomePictureViewCell
        return cell.imageView.image
    }
}

//  自定义首页配图cell
class HMHomePictureViewCell: UICollectionViewCell {
    
    //  MARK:   --懒加载控件
    fileprivate lazy var imageView: UIImageView = {
        
        let imageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        //  按照图片原始比例显示，会出现图片如果过大超出的问题
        imageView.contentMode = .scaleAspectFill
        //  超出本分裁剪掉
        imageView.clipsToBounds = true
        
        return imageView
        
    }()
    
    //  gif图片
    fileprivate lazy var gifImageView = UIImageView(image: UIImage(named: "timeline_image_gif"))
    
    //  需要显示的数据模型
    var picInfo: HMHomePicInfo? {
        didSet {
            
            if let imageUrl = picInfo?.thumbnail_pic {
                imageView.sd_setImage(with: URL(string: imageUrl), placeholderImage: UIImage(named: "timeline_image_placeholder"))
                if imageUrl.hasSuffix(".gif") {
                    //  后缀是.gif显示图片
                    gifImageView.isHidden = false
                } else {
                    //  隐藏
                    gifImageView.isHidden = true
                }
            }
            
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  添加控件设置约束
    private func setUpUI() {
        contentView.addSubview(imageView)
        contentView.addSubview(gifImageView)
        imageView.snp.makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
        gifImageView.snp.makeConstraints { (make) in
            make.bottom.equalTo(imageView)
            make.trailing.equalTo(imageView)
        }
    }
    
}



